// #ifdef SUBSCRIPTION || PRIVATE
import wxInit from '@/common/wxInit';
// #endif
import type pagesJson from '@/pages.json';

type JumpType = 'navigateTo' | 'redirectTo' | 'reLaunch';

type GetArrItemKeyTypes<
	T extends {
		[k: number]: object;
	},
	K extends keyof T[number]
> = T[number][K];

export type RouteJumpPath = GetArrItemKeyTypes<typeof pagesJson.pages, 'path'>;

export type routeJumpEmitObj = {
	name: string;
	value: string | Record<string, any>;
};
export const routeJump = <O extends RouteJumpPath>(url: O, type: JumpType, events?: Parameters<typeof uni.navigateTo>[0]['events'], emitObj?: routeJumpEmitObj) => {
	const handleError = (err:any) => {
		console.warn("跳转参数:",{url,type,events,emitObj})
		console.error("跳转页面错误:",err)
	}
	
	if (url)
		switch (type) {
			case 'navigateTo':
				uni.navigateTo({
					url,
					events,
					success: function (res) {
						// 通过eventChannel向被打开页面传送数据
						emitObj && res.eventChannel.emit(emitObj.name, emitObj.value);
					},
					fail:handleError
				});
				break;
			case 'redirectTo':
				uni.redirectTo({
					url,
					events,
					success: function (res) {
						// 通过eventChannel向被打开页面传送数据
						emitObj && res.eventChannel.emit(emitObj.name, emitObj.value);
					},
					fail:handleError
				});
				break;
			case 'reLaunch':
				uni.reLaunch({
					url,
					events,
					success: function (res) {
						// 通过eventChannel向被打开页面传送数据
						emitObj && res.eventChannel.emit(emitObj.name, emitObj.value);
					},
					fail:handleError
				});
				break;
		}
};


export const goLogin = ({ goToUrl = '', wxJumpType = '1' } = {}) => {
	// #ifdef APP
	routeJump('/pages/public/account/supperAppLogin', 'navigateTo');
	// #endif
	// #ifdef  HTML5 || PREVIEW
	routeJump('/pages/public/account/appLogin', 'navigateTo');
	// #endif
	// #ifdef MP-WEIXIN
	routeJump('/pages/public/account/wxLogin', 'navigateTo');
	// #endif
	// #ifdef MP-ALIPAY
	routeJump('/pages/public/account/aliLogin', 'navigateTo');
	// #endif
	// #ifdef SUBSCRIPTION || PRIVATE

	if (goToUrl) {
		wxInit(true, {
			url: goToUrl,
			type: wxJumpType
		});
	} else {
		wxInit();
	}
	// #endif
};

export const getLayoutTabbarPageUrl = (url: string) => {
	switch (url) {
		case 'home':
			return '/pages/tabbar/index';
		case 'classify':
			return '/pages/classify';
		case 'cart':
			return '/pages/shoppingCart';
		case 'nearby':
			return '/pages/nearby';
		case 'userInfo':
			return '/pages/user';
		
	}
	return '';
};
export const getSwitchLayoutTabbarPageUrl = (url: string) => {
	switch (url) {
		case 'home':
			return '/pages/tabbar/index';
		case 'classify':
			return '/pages/tabbar/classify';
		case 'cart':
			return '/pages/tabbar/shoppingCart';
		case 'nearby':
			return '/pages/tabbar/nearby';
		case 'userInfo':
			return '/pages/tabbar/user';
		
	}
	return '';
};